from torch import nn

from timm.models.sknet import SelectiveKernelBasic

__all__ = ['skresnetcolorspace']


class SKResnetSpaceGenerator(nn.Module):

    def __init__(self, inplanes, planes):
        super(SKResnetSpaceGenerator, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, 64, 3, 1, 1)
        self.act1 = nn.LeakyReLU(True)

        self.block1 = SelectiveKernelBasic(64, 64, 1)
        self.block2 = SelectiveKernelBasic(64, 64, 1)
        self.block3 = SelectiveKernelBasic(64, 64, 1)
        self.block4 = SelectiveKernelBasic(64, 64, 1)
        self.block5 = SelectiveKernelBasic(64, 64, 1)

        self.conv2 = nn.Conv2d(64, 64, 3, 1, 1)
        self.bn2 = nn.BatchNorm2d(64)

        self.conv3 = nn.Conv2d(64, 64, 3, 1, 1)
        self.act3 = nn.LeakyReLU(True)
        self.conv4 = nn.Conv2d(64, planes, 3, 1, 1)

    def forward(self, x):
        x = self.conv1(x)
        x = self.act1(x)
        identity = x

        x = self.block1(x)
        x = self.block2(x)
        x = self.block3(x)
        x = self.block4(x)
        x = self.block5(x)

        x = self.conv2(x)
        x = self.bn2(x)
        x = x + identity

        x = self.conv3(x)
        x = self.act3(x)
        x = self.conv4(x)

        return x


class SKResnetColorSpace(nn.Module):

    def __init__(self, feature_extractor, in_chans, num_classes, pretrained=False):
        super(SKResnetColorSpace, self).__init__()
        self.compact = SKResnetSpaceGenerator(in_chans, 3)
        self.features = feature_extractor(pretrained=pretrained, num_classes=num_classes)

    def forward(self, x):
        x = self.compact(x)
        x = self.features(x)
        return x


def skresnetcolorspace(feature_extractor, in_chans=3, num_classes=1000, pretrained=False):
    model = SKResnetColorSpace(feature_extractor, in_chans=in_chans, num_classes=num_classes, pretrained=pretrained)
    model.default_cfg = model.features.default_cfg
    return model
